/**
 *
 */
$(function () {
    $(document).keyup(function (e) {
        if (e.which == 13) {
            $('#selectBtnEnter').click();
        }
    })
});
var path = '../';
var pageListUrl = path + 'store/detail';
var pageUrl = path + 'store/';
var equipmentCode="";
var id="";
//添加弹窗
var addPanel = null;
var addPanelPicture = null;
// ---------------交互代码begin-----------------
//本页面业务逻辑
var storeRecord = {
    checkLogic: function (dataObj) {
        var isSubmit = true;
        //TODO 逻辑校验，去掉不必要的:
        //检查表单是否存在错误
        $.each(dataObj, function (key) {
            if (key.indexOf('Err') != -1 && dataObj[key].length > 0) {
                return false;
            }
        });
        advInfo.clear(dataObj.workTimeErr);
        if((dataObj.workTime.toString()).match('^[0-9]*$')){
            if((dataObj.workTime.toString()).match('[1-9]\d*')>24){
                dataObj.workTimeErr="营业时间在0-24之间";
                isSubmit=false;
            }
        }else{
            dataObj.workTimeErr="输入的数据必须为数字";
            isSubmit=false;
        }
        return isSubmit;
    },
    checkFileType: function () {
        var fileName = $("#file")[0].files[0].name;
        var fileType = fileName.substr(fileName.lastIndexOf(".") + 1, fileName.length);
        if (fileType.toUpperCase() != 'XLSX' && fileType.toUpperCase() != 'XLS') {
            importVue.fileErr = "请选择*.xlsx或者*.xls格式的Excel文件";
            return false;
        }
        return true;
    }
};
//本页面业务逻辑
var advInfo = {
    checkLogic: function (dataObj, err, fg) {
        advInfo.clear(err);
        console.log(dataObj)
        var isSubmit = true;
        var topImg = $("#topImg")[0].files[0];
        //文件空校验
        if (!topImg) {
            err.topImgErr = "请上传图片";
            isSubmit = false;
        }
        //文件格式校验
        var imgType = ["jpg", "png", "gif", "jpeg", "bmp"];
        var videoType = ["mp4", "avi", "mov", "asf", "wmv", "rm"];
        var musicType = ["mp3"];
        // if(topImg && bottomImg && middleVideo){
        if (topImg) {
            var type = topImg.name.substr(topImg.name.lastIndexOf(".") + 1, topImg.name.length).toLowerCase();
            if ($.inArray(type, imgType) == '-1') {
                err.topImgErr = "请上传" + imgType.toString() + "格式的图片";
                isSubmit = false;
            }
        }
        console.log(err)
        //检查表单是否存在错误
        $.each(err, function (key) {
            if (key.indexOf('Err') != -1 && err[key].length > 0) {
                return false;
            }
        });
        return isSubmit;
    },
    clear: function (obj) {
        $.each(obj, function (key) {
            if ($.isArray(obj[key])) {
                obj[key] = [];
            } else {
                obj[key] = "";
            }
        });
    }
};
//绑定列表List---begin----所有的操作都围绕列表展开，新增、更新其他比较独立 
var dataList = new Vue({
    el: "#storeRecordList",
    data: {
        pageInfo: {},
        detail: {},
        //TODO 自定义条件查询---begin--------
        condition: {
            page: 1,
            rows: customUtils.pageSize,
            total: 0,
            traffic: 0,
            environment: 0,
            surface: 0,
            display: 0,
            quality: 0,
            attitude: 0,
            installStatus: 0,
            sign: 0,
            shopEquipmentStatus: "",
            workTime: "",
            standardOpenTime: "",
            areaType: "",
            flowRate: "",
            address: "",
            contacts: "",
            shopInfo: "",
            customers: "",
            customerHighTime: "",
            shopImage1: "",
            shopImage2: "",
            shopImage3: "",
            shopImage4: "",
            shopImage5: "",
            equipmentCode:"",
            errorDate: "",
            phoneCommunicationRecord: "",
            instructorCommunicationRecord: "",
            visitRecord: "",
            errorReason: "",
            errorPhenomenon: "",
            processingMethod: "",
            processingResult: "",

            items: [],
            all: false,
            key: "",
            province: "",
            city: "",
            area: "",
            statusOk: "",
            statusNo: "",
            Percentage: "",
            provinces: [],
            citys: [],
            areas: [],
            id: "",
            postionCode: "",
            shopCode: "",
            companyName: "",
            shopName: "",
            shopContacts: "",
            shopPhone: "",
            empno: "",
            address: "",
            createdBy: "",
            createdDate: "",
            updatedBy: "",
            updatedDate: "",
            installPhoto: "",
            installDate: "",
            flowRate: "",
            status: "",
        },
        //自定义条件查询---end--------
        selectIds: [],//多选
        showSuccess: false,//false不显示成功提示
        selectedIdx: -1,//保存操作行的索引
        isSearch: false,//init:页面初始化；search:点击查询；paging:点击翻页；changePageSize:改变页面显示条数
        selectedPageSize: customUtils.pageSize//修改页面数据显示条数
    },
    mounted: function () {
        this.getParams();
    },
    // 在 `methods` 对象中定义方法,如果操作中函数的逻辑比较复杂，必须封装到dictType对象
    methods: {
        selectChkBtn: function (e) {//用于多选事件
            this.selectIds.push($(e.target).val());
        },
        getParams:function (){
            var self =this;
            var url=window.location.search;
            this.id=url.substr(url.indexOf("id=")+"id=".length,url.indexOf("&")-"id=".length-1)
            equipmentCode=url.substr(url.indexOf("equipmentCode=")+"equipmentCode=".length)
            console.log(this.id)
            id=this.id;
            this.clickAction(this.id)
        },
        clickAction: function (id) {
            var url = pageUrl + 'id/' + id;
            var self = this;
            customUtils.get(self.$http, url, function (response, isSuccess) {
                if (isSuccess == false) {
                    return;
                }
                dataList.detail = response.body;
            }, function (response) {
                console.log(response);
            });
            this.getList('search',equipmentCode);
        },
        getAreaData: function () {
            this.$http.get("../appInfo/queryAreaTree").then(function (response) {
                console.log(response)
                dataList.$data.condition.provinces = response.body;
                console.log(dataList.$data)
            }, function (res) {

            });
        },
        setCitys: function () {
            dataList.$data.condition.citys = dataList.$data.condition.province.citys;
            dataList.$data.condition.city = "";
            dataList.$data.condition.area = "";
        },
        setAreas: function () {
            dataList.$data.condition.areas = dataList.$data.condition.city.areas;
            dataList.$data.condition.area = "";
        },
        //搜索、分页列表
        getList: function (eventSrc) {
            var self = this;
            //改变页面显示条数
            if (eventSrc == "changePageSize") {
                if (this.pageInfo.pageSize != this.selectedPageSize) {
                    this.pageInfo.pageSize = this.selectedPageSize;
                    $('#pagination').jqPaginator('destroy');
                    eventSrc = 'init';//重新绘制控件
                } else {
                    return;
                }
            }
            var param = {"page": 1, "rows": customUtils.pageSize};
            //初始化时无当前页数，后台有默认第1页，每页10条
            if (this.pageInfo != undefined && this.pageInfo.pageNum != undefined) {
                self.condition["page"] = this.pageInfo.pageNum;
                self.condition["rows"] = this.pageInfo.pageSize;
            }
            param["page"] = self.condition["page"];
            param["rows"] = self.condition["rows"];
            param["equipmentCode"] = equipmentCode;
            this.condition.items = [];
            console.log(param)
            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self, pageListUrl, param, function (response, isSuccess) {
                if (isSuccess == false) {
                    dataList.pageInfo.pages = 0;
                    customUtils.noData('无数据', 0);
                    return;
                }
                dataList.pageInfo = response.body.pagination;
                customUtils.noData('无数据', dataList.pageInfo.pages);
                //页面初始化、搜索时，才需要执行分页控件
                if (eventSrc == 'init' || eventSrc == 'search') {
                    customUtils.paging('#pagination', dataList.pageInfo.pages, customUtils.showPage, function (num) {
                        //当前页码pageNum与将要翻页的页码num不相等才执行，否则为同一页
                        if (dataList.pageInfo.pageNum != num) {
                            dataList.pageInfo.pageNum = num;
                            dataList.getList('paging');
                        }
                    });
                }
            }, function (response) {
                console.log(response);
                dataList.pageInfo.pages = 0;
                customUtils.noData('无数据', 0);
            });
        },
        importPostion: function () {
            var obj3 = document.getElementById('file');
            obj3.outerHTML = obj3.outerHTML;
            importVue.fileErr = "";
            importPanel = layer.open({
                type: 1,
                title: "导入位置信息",
                area: ['600px', '70%'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#importPanel')
            });
            console.log(addOrUpdate.$data.field)
        },
        addOrUpdatePanelPicture: function (flag1) {
            var flag=flag1.split("+");
            var obj1 = document.getElementById('topImg');
            obj1.outerHTML = obj1.outerHTML;
            advInfo.clear(addOrUpdate.$data.err);
            advInfo.clear(addOrUpdate.$data.field);
            console.log(addOrUpdate.$data.field)
            addPicture.$data.field.equipmentCode=equipmentCode;
            addPicture.$data.field.id=this.id;
            if(flag[1]=='shopImage1'){
                addPicture.$data.field.shopImage1='shopImage1'
            }else if(flag[1]=='shopImage2'){
                addPicture.$data.field.shopImage2='shopImage2'
            }else if(flag[1]=='shopImage3'){
                addPicture.$data.field.shopImage3='shopImage3'
            }else if(flag[1]=='shopImage4'){
                addPicture.$data.field.shopImage4='shopImage4'
            }else if(flag[1]=='shopImage5'){
                addPicture.$data.field.shopImage5='shopImage5'
            }
            if (flag[0] != 'update') {
                addPicture.$data.field.param1 = "1";
                $(".t11").hide();
            } else {
                $(".t12").show();
            }
            var tmpTitle = flag[0] == "add" ? "添加" : "修改";
            addOrUpdate.typeChange()
            addPanelPicture = layer.open({
                type: 1,
                title: tmpTitle + "门店图片上传",
                area: ['650px', '80%'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#addPanelPicture')
            });
            console.log(addPanelPicture)
        },
        //更新状态
        updateStatus: function (status) {
            var size = dataList.condition.items.length;
            if (size <= 0) {
                return;
            }
            var str = status == 1 ? "有效" : "无效";
            var msg = "您确定要将" + size + " 条位置信息置为<" + str + ">状态";
            var self = this;
            layer.confirm(msg, function (index) {
                var param = {};
                param["items"] = JSON.stringify(dataList.condition.items);
                param["status"] = status;
                customUtils.post(self, pageUrl + "/updateStatus", param, function (response, isSuccess) {
                    dataList.getList('no');
                }, function (response) {
                    customUtils.showRequestTips(response, 3000)
                });
                layer.close(index);
                return true;
            });
            return false;
        },
        //初始化更新，更新对话框
        updateInit: function (index) {
            //先显示窗口，才有加载效果
            this.addOrUpdatePanel("update");
            var url = pageUrl + 'id/' + id;
            var self = this;
            customUtils.get(self.$http, url, function (response, isSuccess) {
                if (isSuccess == false) {
                    return;
                }
                //回显表单数据
                $.each(response.body, function (key) {
                    if (addOrUpdate[key] !== undefined && response.body[key]) {
                        addOrUpdate[key] = response.body[key];
                    }
                });
            }, function (response) {
                console.log(response);
            });
        },
        checkAll: function () {
            console.log(this.condition);
            if (this.condition.all) {
                this.condition.all = false;
                $("tbody").find("input[type='checkbox'][name='id']").each(function (i, val) {
                    dataList.condition.items = [];
                });
            } else {
                this.condition.all = true;
                $("tbody").find("input[type='checkbox'][name='id']").each(function (i, val) {
                    dataList.condition.items[i] = val.value;
                });
            }
        },


        //打开添加对话框
        addOrUpdatePanel: function (flag) {
            //清除表单数据，否则会有前一条修改数据的内容
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
            var tmpTitle = flag == "add" ? "添加" : "修改";
            addPanel = layer.open({
                type: 1,
                title: tmpTitle + "门店图片",
                area: ['570px', 'auto'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#addPanel')
            });
        },
        reset: function () {
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
        }
    }
});
//绑定列表List---end---- 

//新增或更新---------begin-------
var addPicture = new Vue({
    el: "#addPanelPicture",
    data: {
        postionCode: "",
        shopCode: "",
        companyName: "",
        shopName: "",
        traffic: 0,
        environment: 0,
        surface: 0,
        display: 0,
        quality: 0,
        attitude: 0,
        installStatus: 0,
        sign: 0,
        shopEquipmentStatus: "",
        workTime: "",
        standardOpenTime: "",
        areaType: "",
        flowRate: "",
        address: "",
        contacts: "",
        shopInfo: "",
        customers: "",
        customerHighTime: "",
        shopImage1: "",
        shopImage2: "",
        shopImage3: "",
        shopImage4: "",
        shopImage5: "",
        updatedBy: "",
        updatedDate: "",
        equipmentCode:"",
        id: "",
        //以下是错误信息
        postionCodeErr: "",
        shopCodeErr: "",
        companyNameErr: "",
        shopNameErr: "",
        trafficErr: 0,
        environmentErr: 0,
        surfaceErr: 0,
        displayErr: 0,
        qualityErr: 0,
        attitudeErr: 0,
        installStatusErr: 0,
        signErr: 0,
        updatedByErr: "",
        showSuccess: true,//显示成功提示
        field: {
            id: "",
            advCode: "",
            positionCode: "",
            param1: "",
            shopImage1: "",
            shopImage2: "",
            shopImage3: "",
            shopImage4: "",
            shopImage5: "",
            advType: "3",
            maxAge: "",
            minAge: "",
            sex: "2",
            topImg: "",
            bottomImg: "",
            middleVideo: "",
            price: ""
        },
        //错误信息
        err: {
            positionCodeErr: "",
            advCodeErr: "",
            advNameErr: "",
            maxAgeErr: "",
            minAgeErr: "",
            sexErr: "",
            advPathErr: "",
            topImgErr: "",
            bottomImgErr: "",
            middleVideoErr: "",
            advTypeErr: "",
            priceErr: ""
        }
    },
    //当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch: {},
    methods: {
        changeTime: function (elem) {
            addOrUpdate[elem.split('-')[0]] = $("#" + elem).val();
        },
        save: function () {
            //逻辑校验
            if (!storeRecord.checkLogic(this.$data)) {
                return;
            }
            //没有id的时候表示新增，否则为更新
            var actionUrl = this.id == "" ? 'save' : 'update';
            var self = this;
            customUtils.post(self, pageUrl + actionUrl, self.$data, function (response, isSuccess) {
                if (actionUrl == 'update') {
                    var record = dataList.pageInfo.list[dataList.selectedIdx];
                    //更新成功，刷新列表中对应的数据
                    $.each(record, function (key) {
                        if (addOrUpdate[key] != undefined) {
                            record[key] = addOrUpdate[key];
                        }
                    });
                } else if (isSuccess) {
                    dataList.getList('init');
                }
                if (isSuccess && addPanel) layer.close(addPanel);
            }, function (res) {
                //console.log(response.body);
            });
        },
        savePicture: function () {
            //没有id的时候表示新增，否则为更新
            var actionUrl = this.field.id == "" ? 'save' : 'update';
            //逻辑校验
            if (!advInfo.checkLogic(this.$data.field, this.$data.err, actionUrl)) {
                return;
            }
            var self = this;
            var formDate = new FormData($("#addPanelPicture")[0]);
            console.log(self.$data)
            customUtils.post(self, pageUrl + "savePicture", formDate, function (response, isSuccess) {
                customUtils.showTips(response.body, addOrUpdate.$data.err)
                dataList.getList('init');
                if (isSuccess && addPanelPicture) layer.close(addPanelPicture);
            }, function (res) {
                //console.log(response.body);
            });
        },
        //清除表单数据
        reset: function () {
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
        },
        resetPicture: function () {
            if (addPanelPicture) layer.close(addPanelPicture);
        }
    }
});


//新增或更新---------begin-------
var addOrUpdate = new Vue({
    el: "#addPanel",
    data: {
        equipmentCode:"",
        postionCode: "",
        shopCode: "",
        companyName: "",
        traffic: 0,
        environment: 0,
        surface: 0,
        display: 0,
        quality: 0,
        attitude: 0,
        installStatus: 0,
        sign: 0,
        shopEquipmentStatus: "1",
        workTime: "",
        standardOpenTime: "",
        areaType: "",
        flowRate: "",
        address: "",
        contacts: "",
        shopInfo: "",
        customers: "",
        customerHighTime: "",
        shopImage1: "",
        shopImage2: "",
        shopImage3: "",
        shopImage4: "",
        shopImage5: "",
        updatedBy: "",
        updatedDate: "",
        id: "",
        //以下是错误信息
        postionCodeErr: "",
        shopCodeErr: "",
        companyNameErr: "",
        shopNameErr: "",
        shopNameErr: "",
        workTimeErr: "",
        shopInfoErr: "",
        customersErr: "",
        customerHighTimeErr: "",
        updatedByErr: "",
        updatedDateErr: "",
        showSuccess: true,//显示成功提示
        field: {
            id: "",
            advCode: "",
            positionCode: "",
            param1: "",
            advType: "3",
            maxAge: "",
            minAge: "",
            sex: "2",
            topImg: "",
            bottomImg: "",
            middleVideo: "",
            price: ""
        },
        //错误信息
        err: {
            positionCodeErr: "",
            workTimeErr: "",
            advCodeErr: "",
            advNameErr: "",
            maxAgeErr: "",
            minAgeErr: "",
            sexErr: "",
            advPathErr: "",
            topImgErr: "",
            bottomImgErr: "",
            middleVideoErr: "",
            advTypeErr: "",
            priceErr: ""
        }
    },
    //当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch: {},
    methods: {
        changeTime: function (elem) {
            addOrUpdate[elem.split('-')[0]] = $("#" + elem).val();
        },
        save: function () {
            //逻辑校验
            if (!storeRecord.checkLogic(this.$data)) {
                return;
            }
            //没有id的时候表示新增，否则为更新
            var actionUrl = this.id == "" ? 'save' : 'update/detail';
            var self = this;
            self.equipmentCode=equipmentCode;
            customUtils.post(self, pageUrl + actionUrl, self.$data, function (response, isSuccess) {
                if (actionUrl == 'update/detail') {
                    dataList.clickAction(id);
                } else if (isSuccess) {
                    dataList.clickAction(id);
                }
                if (isSuccess && addPanel) layer.close(addPanel);
            }, function (res) {
            });
        },
        typeChange: function () {
            var b = addOrUpdate.$data.field.advType;
            if (b == 6) {
                $("#t1").hide();
                $("#t2").show();
            } else {
                $("#t1").show();
                $("#t2").hide();
            }
        },
        savePicture: function () {
            //没有id的时候表示新增，否则为更新
            var actionUrl = this.field.id == "" ? 'save' : 'update';
            //逻辑校验
            if (!advInfo.checkLogic(this.$data.field, this.$data.err, actionUrl)) {
                return;
            }
            var self = this;
            var formDate = new FormData($("#addPanelPicture")[0]);
            console.log(self.$data)
            customUtils.post(self, pageUrl + "savePicture", formDate, function (response, isSuccess) {
                customUtils.showTips(response.body, addOrUpdate.$data.err)
                dataList.getList('init');
                if (isSuccess && addPanelPicture) layer.close(addPanelPicture);
            }, function (res) {
                //console.log(response.body);
            });
        },
        //清除表单数据
        reset: function () {
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
        },
        resetPicture: function () {
            if (addPanelPicture) layer.close(addPanelPicture);
        }
    }
});

//新增或更新---------end-------

var importVue = new Vue({
    el: "#importPanel",
    data: {
        fileErr: ""
    },
    methods: {
        importB: function () {
            var self = this;
            if (!storeRecord.checkFileType()) {
                return;
            }
            console.log($("#importPanel"))
            console.log($("#importPanel").find("#file")[0].files)
            var formDate = new FormData($("#importPanel")[0]);
            //没选择文件时
            if ($("#importPanel").find("#file")[0].files.length <= 0) {
                $(".errMsg").html("请选择要上传的数据文件");
                return;
            }
            customUtils.post(self, pageUrl + "upload", formDate, function (response) {
                console.log(response);
                customUtils.showTips(response.body, null, 2000);
                var html = "";
                if (response.body.errList != 'undefined' && response.body.errList != '' && response.body.errList != null) {
                    response.body.errList.forEach(function (value, index) {
                        html = html + value + "<br>";
                    });
                    $(".errMsg").html(html);
                } else {
                    if (importPanel) layer.close(importPanel);
                    dataList.getList('init');
                }
            }, function (response) {
                customUtils.showRequestTips(response, 3000)
            })
            console.log(formDate);
        }
    }

});
